package com.nn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nn.R;
import com.nn.entity.SysRole;
import com.nn.entity.SysUser;
import com.nn.entity.SysUserRole;
import com.nn.mapper.SysUserMapper;
import com.nn.service.SysUserRoleService;
import com.nn.service.UserService;
import com.nn.utils.BeanCopyUtils;
import com.nn.utils.SecurityUtils;
import com.nn.vo.PageVO;
import com.nn.vo.UserIRolesVO;
import com.nn.vo.UserInfoVO;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;



/**
 *
 * @author 年年
 * @// TODO: 2022/11/16  00:42
 */
@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements UserService {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysUserRoleService userRoleService;


    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public R register(SysUser user) {
        //校验数据
        if(!StringUtils.hasText(user.getUserName()))
            throw new RuntimeException("请输入用户名");
        if(!StringUtils.hasText(user.getPassword()))
            throw new RuntimeException("请输入密码");
        if(!StringUtils.hasText(user.getEmail()))
            throw new RuntimeException("请输入邮箱");
        if(!StringUtils.hasText(user.getNickName()))
            throw new RuntimeException("请输入姓名");
        //判断用户名和邮箱是否再数据库存在
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName,user.getUserName());
        SysUser userResult = userMapper.selectOne(queryWrapper);
        if(!Objects.isNull(userResult))
            throw new RuntimeException("该用户名已存在");
        LambdaQueryWrapper<SysUser> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(SysUser::getEmail,user.getEmail());
        SysUser emailResult = userMapper.selectOne(queryWrapper2);
        if(!Objects.isNull(emailResult))
            throw new RuntimeException("该邮箱已被注册");
        //对密码进行加密
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        userMapper.insert(user);
        return R.okResult();
    }


    /**
     * 更新个人资料
     * @param user
     * @return
     */
    @Override
    public R updateUserInfo(SysUser user) {
        if (Objects.isNull(user))
            throw new RuntimeException("请输入正确的个人信息");
        Long id = user.getId();
        if(user.getRoleIds()!=null){
            for(Long itm : user.getRoleIds()){
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(id);
                userRole.setRoleId(itm);
                userRoleService.saveOrUpdate(userRole);
            }
        }
        userMapper.updateById(user);
        return R.okResult();

    }


    /**
     * 查询个人信息
     * @return
     */
    @Override
    public R selectUserInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据id查询用户数据
        SysUser User = userMapper.selectById(userId);
        //封装对应的vo
        UserInfoVO userInfoVO = BeanCopyUtils.copyBean(User, UserInfoVO.class);
        return R.okResult(userInfoVO);
    }


    /**
     * 用户信息查询
     * @param pageNum
     * @param pageSize
     * @param userName
     * @param phoneNumber
     * @param status
     * @return
     */
    @Override
    public R pageList(Integer pageNum, Integer pageSize, String userName, String phoneNumber, String status) {
        Page<SysUser> pageInfo = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(userName!=null,SysUser::getUserName,userName)
                .like(phoneNumber!=null,SysUser::getPhonenumber,phoneNumber)
                .eq(SysUser::getDelFlag,0);
        page(pageInfo,queryWrapper);
        PageVO result = new PageVO(pageInfo.getRecords(),pageInfo.getTotal());
        return R.okResult(result);
    }




    /**
     * 设置停用启用
     * @param
     * @return
     */
    @Override
    public R updateStatus(Long id,String status) {
        SysUser   user = new SysUser();
        user.setId(id);
        user.setStatus(status);
        updateById(user);
        return R.okResult();
    }


    /**
     * 根据id查用户信息
     * @param id
     * @return
     */
    @Override
    public R selectUserInfoById(Long id) {
        //查询用户关联的角色id列表
        List<Long> roleList = userMapper.selectUserJoinRole(id);
        //查询所有角色列表
        List<SysRole> RoleAll = userMapper.selectRoleAll();
        //查询用户信息
        SysUser user= userMapper.selectUserByID(id);
        UserIRolesVO result = new UserIRolesVO(roleList,RoleAll,user);
        return R.okResult(result);
    }


    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public R addUser(SysUser user) {
        //插入用户信息
        save(user);
        //插入角色信息
        Long id = user.getId();//获取id
        for (Long i : user.getRoleIds()){
            SysUserRole userRole = new SysUserRole(id,i);
            userRoleService.save(userRole);
        }
        return R.okResult();
    }


    /**
     * 删除用户
     * @param ids
     * @return
     */
    @Override
    public R deleteUser(List<Long> ids) {
        getBaseMapper().deleteBatchIds(ids);
        for (Long id:ids){
            LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserRole::getUserId,id);
            userRoleService.remove(queryWrapper);
        }
        return R.okResult();
    }
}
